import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
// 切换项目目录 安装  npm install --save nprogress
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// 移除小圆圈加载进度
NProgress.configure({ showSpinner: false });
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    meta:{keep:true},//需要缓存
    component: HomeView
  },
  {
    path: '/echart',
    name: 'echart',
    component: ()=>import('@/views/ChartView.vue')
  },
  {
    path: '/fake',
    name: 'fake',
    component: ()=>import('@/views/FakeView.vue')
  },
  {
    path: '/map1',
    name: 'map1',
    component: ()=>import('@/views/MapView1.vue')
  },
  {
    path: '/map2',
    name: 'map2',
    component: ()=>import('@/views/MapView2.vue')
  },
  {
    path: '/product/:id',
    name: 'product',
    // 自己定义的路由meta元信息(没有tabBar)
    meta:{noTabBar:true},
    component:()=>import('@/views/ProductView.vue')
  },
  {
    path: '/searchlist',
    meta:{noTabBar:true},
    name: 'searchlist',     
    component:()=>import('@/views/SearchList.vue')
  },
  {
    path: '/category',
    meta:{keep:true},//需要缓存
    name: 'category',     
    component:()=>import('@/views/CategoryView.vue')
  },
  {
    path: '/ball',
    name: 'ball',
    component:()=>import('@/views/BallView.vue')
  },
  {
    path: '/cart',
    name: 'cart',
    // beforeEnter: (to, from, next) => {
    //   console.log("进入购物车",to,from)
    //   next(true)
    // },
    meta:{
      requireAuth:true,
      noTabBar:true
    },
    component:()=>import('@/views/CartView.vue')
  },
  {
    path: '/user',
    name: 'user',
    meta:{
      requireAuth:true,//需要权限
    },
    component:()=>import('@/views/UserView.vue')
  },
  {
    path: '/login',
    meta:{keep:true},//需要缓存
    name: 'login',
    component:()=>import('@/views/LoginView.vue')
  },
  {
    path: '/feedback',
    name: 'feedback',
    component:()=>import('@/views/FeedBack.vue')
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  }
]
const router = new VueRouter({
  routes
})
// 全局导航守卫（每个页面进入，离开都会触发）
router.beforeEach((to,from,next)=>{
  NProgress.start();
  // console.log(to,from);
  // next(true);//next一定要执行
  // 如果要去的页面meta有requireAuth属性
  if(to.meta.requireAuth){
    // 判断用户是否登录
    if(localStorage.getItem("token")){
      // 如果有token 认为已经登录
      next();
    }else{
      // 否则跳转到登录并携带查询参数redirect值是本来要去页面的path
      next("/login?redirect="+to.path)
    }
  }else{
    // 否则直接放行
    next();
  }
})
router.afterEach(()=>{
  // console.log("页面切换完毕");
  NProgress.done();
})

export default router
